//
//  CDPreviewViewController.swift
//  PDF
//
//  Created by dong chang on 2024/3/27.
//

import UIKit
import SignatureView

class CDPreviewViewController: CDBaseAllViewController,UICollectionViewDelegate,
                               UICollectionViewDataSource {

    var isEditDone = false
    var previewImages:[UIImage] = []
    public var currentIndex: Int = 1
    private var collectionView: UICollectionView!

    lazy var editView: CDPreViewEditView = {
        let height: CGFloat = UIDevice.safeAreaBottom() > 0 ? 192 : 160
        
        let tmpV = CDPreViewEditView(frame: CGRect(x: 0, y: CDViewHeight - height, width: CDSCREEN_WIDTH, height: height))
        self.view.addSubview(tmpV)
        self.view.bringSubviewToFront(tmpV)
        tmpV.didSelectHanlder = {[weak self] option , isApplyAllPage in
            guard let self = self else {
                return
            }
            if option == .effect {
                
            } else {
                self.didSelect(option: option)
            }
        }

        return tmpV
    }()

    
    lazy var deleteAlert: CDDeleteAlert = {
        let tmpV = CDDeleteAlert()
        tmpV.actionHandler = { [weak self] in
            guard let self = self else {
                return
            }
            self.previewImages.removeFirst(self.currentIndex)
            self.collectionView.reloadData()
            self.editView.controlBar.titelLabel.text = "\(currentIndex + 1)/\(previewImages.count)"

        }
        return tmpV
    }()
    
    lazy var waterMark: CDWaterToolView = {
        let nib = UINib(nibName: "CDWaterToolView", bundle: nil)
        let tmpV = nib.instantiate(withOwner: self, options: nil).first as! CDWaterToolView
        tmpV.frame = CGRect(x: 0, y: CDViewHeight, width: CDSCREEN_WIDTH, height: 240)
        tmpV.backgroundColor = .white
//        tmpV.actionHandler = { [weak self] in
//            guard let self = self else {
//                return
//            }
//            self.previewImages.removeFirst(self.currentIndex)
//            self.collectionView.reloadData()
//            self.editView.controlBar.titelLabel.text = "\(currentIndex + 1)/\(previewImages.count)"
//
//        }
        self.view.addSubview(tmpV)
        return tmpV
    }()
    
    
    lazy var signature: SignatureView = {
        let tmp = SignatureView(frame: CGRect(x: 0, y: 0, width: CDSCREEN_WIDTH, height: CDSCREEN_HEIGTH))
        return tmp
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let cancel = UIButton(type: .app_back)
        cancel.addTarget(self, action: #selector(onCancelAction), for: .touchUpInside)
        cancel.frame = CGRect(x: 16, y: 16, width: 32, height: 32)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: cancel)
        
        let export = UIButton(type: .done)
        export.addTarget(self, action: #selector(onDoneAction), for: .touchUpInside)
        export.size = CGSize(width: 80, height: 32)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: export)
        
        if previewImages.count > 0 {
            editView.controlBar.titelLabel.text = "1/\(previewImages.count)"
        }else {
            editView.controlBar.titelLabel.text = "0/\(previewImages.count)"
        }
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: CDSCREEN_WIDTH, height: self.editView.minY)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: CDSCREEN_WIDTH, height: self.editView.minY), collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .baseBgColor
        self.view.addSubview(collectionView)
        collectionView.register(CDImageScrollerCell.self, forCellWithReuseIdentifier: "CDImageScrollerCell")
        collectionView.contentInsetAdjustmentBehavior = .scrollableAxes
        collectionView.isPagingEnabled = true
        collectionView.reloadData()
    }
    
    
    
    
    @objc func onCancelAction() {
        let alert = UIAlertController(title: "Warn".localize(), message: "Are you sure to give up the editing".localize(), preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Cancel".localize(), style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Sure".localize(), style: .default, handler: { (_) in
            self.dismiss(animated: true)
            
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    @objc func onDoneAction() {
       let export = CDExportViewController()
        export.images = previewImages
        let nsv = CDNavigationController(rootViewController: export)
        nsv.modalPresentationStyle = .fullScreen
        self.present(nsv, animated: true)
    }
    
    func didSelect(option: CDTextEditOptions) {
        switch option {
        case .addpage:
            CDImportTools.importPhotoFromLibrary(viewController: self) { [weak self] images in
                guard let self = self else {
                    return
                }
                var index = currentIndex
                for img in images {
                    self.previewImages.insert(img, at: index)
                    index += 1
                }
                self.collectionView.reloadData()
                self.editView.controlBar.titelLabel.text = "\(self.currentIndex + 1)/\(previewImages.count)"

            }
        case .crop:
            break
        case .rotate:
            break
        case .ocr:
            let ocr = CDOCRViewController()
            let nav = CDNavigationController(rootViewController: ocr)
            self.present(nav, animated: true)
        case .waterMark,.addText:
            self.waterMark.updateUI(isWater: option == .waterMark)
            self.waterMark.show()
        case .signature:
            let sig = CDSignatureViewController()
            sig.modalPresentationStyle = .fullScreen
            self.present(sig, animated: true)
        case .encription:
            break
        case .delete:
            self.deleteAlert.show()
        default:
            break
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return previewImages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let image = previewImages[indexPath.item]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CDImageScrollerCell", for: indexPath) as! CDImageScrollerCell
        cell.setImage(image: image)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        guard let firstIndexPath = collectionView.indexPathsForVisibleItems.first else {
            return
        }
        currentIndex = firstIndexPath.item
        editView.controlBar.titelLabel.text = "\(currentIndex + 1)/\(previewImages.count)"

    }
}
